package com.bdqn.controller;

import com.bdqn.entity.CommonResult;
import com.bdqn.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class OrderController {
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient; //注：导第二个包(长的)
    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
//参数一为 url 请求地址，参数二为请求参数，参数三为返回值类型
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,
                CommonResult.class); //写操作
    }
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
//        String serviceName = "CLOUD-PAYMENT-SERVICE"; //我们之前在注册中心看到这个服务名是大写，因为这里不区分大小写
//        List<ServiceInstance> instance = this.discoveryClient.getInstances(serviceName);
//        if (instance.isEmpty()) {
//            return null;
//        }
//        //为了演示，在这里只获取一个实例
//        ServiceInstance serviceInstance = instance.get(0);
//        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
//        return restTemplate.getForObject("http://" + url + "/payment/get/"+id,CommonResult.class);
    }
}
